(function(w){

	
	wxCloud
	.cloud()
	.callContainer({

		path:'/container-login/?type=jsapi&ht=1',
		method:'GET',
		success:function(data){

			login()

	    	SDKyanzheng(data.data)

	    	var title = document.title
	    	var url = location.href
	    	var imgUrl=$('#zhandianIcon').attr('href')
	    	var desc='237 医治 顶峰'

	    	fenxiang(title,url,imgUrl,desc) //分享设置

	    	wx.error(function(){

	    		wxCloud
				.cloud()
				.callContainer({

					path:'/container-login/?type=jsapi&ht=0',
					method:'GET',
					success:function(data){
	    				location.reload();
	    			}
				})

	    	})

		}
	})

	
	function login(){ //登录模块

		lsa.get('refresh_token') == null?lsa.set('refresh_token','null'):''

		// lsa.set('refresh_token','123456789')

	    if(lsa.get('refresh_token') !== 'null'){

	    	wxCloud
			.cloud()
			.callContainer({

				path:'/container-login/?type=getuserInfo_refresh_token&refresh_token='+ lsa.get('refresh_token'),
				method:'GET',
				success:function(data){

	        		 // console.log(data.data)

	        		 // alert(lsa.get('refresh_token'))

	        		 // alert(data.data)

	                 var userInfo = JSON.parse(data.data)

	                 if(userInfo.refresh_token == null){  //如果热刷新失效则进行重新登录

	                 	$("#nickname").text('点击头像登录')

	                 	$("#headimgurl img").attr('src',"https://srrz-2g24l1oea7a7e67e-1304952114.tcloudbaseapp.com/sgb2.0/img/%E5%A4%B4%E5%83%8F.png")

	                 	shouQuan("#shoquan")

	                 	return
	                 }

	                 $("#nickname").text(userInfo.nickname)
	                 $("#headimgurl img").attr('src',userInfo.headimgurl)
	                 lsa.set('refresh_token',userInfo.refresh_token)

				}

	    	})
	    
	    }else{

	    	shouQuan("#shoquan")
	}


	function shouQuan(eleId){


		$(eleId).click(function () {

    		var redirect_uri = encodeURI(location.href).replace(/#.+/,"")

    		var state = "111"

    		var appid = "wx258fd99a593928a8"

    		var scope = "snsapi_userinfo"

            var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid +"&redirect_uri=" + redirect_uri + "&response_type=code&scope=" + scope + "&state=" + state + "#wechat_redirect"

            // alert(url)

            window.location.href=url

     	})


     	var code = getQueryVariable("code"); 

        if(code){

        	if(lsa.get('code')!==code){

        		lsa.set('code',code)
        		wxCloud
				.cloud()
				.callContainer({

					path:'/container-login/?type=get_authorization_code&code='+ code,
					method:'GET',
					success:function(data){

	            		// console.log(data.data)

	                     var userInfo = JSON.parse(data.data)

		                     wxCloud.cloud().callFunction({
		                     	name:"sgb-login-user-info-add",
		                     	data:userInfo,
		                     	success:function(res){
		                     		// alert('上传成功')
		                     		// alert(JSON.stringify(res))
		                     	},
		                     	fail:function(erro){
		                     		// alert('上传失败')
		                     		// console.log('erro=>',erro)
		                     	}
		                     })


		                     $("#nickname").text(userInfo.nickname)
			                 $("#headimgurl img").attr('src',userInfo.headimgurl)
			                 lsa.set('refresh_token',userInfo.refresh_token)
			                 lsa.set('openid',userInfo.openid)

					}

	        	})
        	}


        }

	}

	}


	function SDKyanzheng(jsapi_ticket){ //微信验证

		var nonceStr = 'Wm3WZYTPz0wzccnW'

		var ts = Math.round(new Date().getTime() / 1000).toString()

		var url = window.location.href

    	var string1 = 'jsapi_ticket='+jsapi_ticket+'&noncestr='+nonceStr+'&timestamp='+ts+'&url='+url

    	var data = {

    		jsapi_ticket:jsapi_ticket,
    		noncestr:nonceStr,
    		timestamp:ts,
    		url:url
    	}

    	var signature = SHA1(objKeySort(data))

    	wx.config({
    	  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    	  appId: 'wx258fd99a593928a8', // 必填，公众号的唯一标识
    	  timestamp: ts, // 必填，生成签名的时间戳
    	  nonceStr: nonceStr, // 必填，生成签名的随机串
    	  signature: signature,// 必填，签名
    	  jsApiList: ['updateTimelineShareData','updateAppMessageShareData'] // 必填，需要使用的JS接口列表
    	});


	}

	function fenxiang(title,link,imgUrl,desc=''){ //设置分享朋友圈和微信朋友功能
 
		wx.ready(function () {

			wx.updateTimelineShareData({ 
		        title: title, // 分享标题
		        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		        imgUrl: imgUrl, // 分享图标
		        success: function () {
		          // 设置成功


		        }
		      })

	        wx.updateAppMessageShareData({ 

	            desc: desc, // 分享描述
	            title: title, // 分享标题
		        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		        imgUrl: imgUrl, // 分享图标
	            success: function () {
	              // 设置成功

	            }
	         })
	    })
	            
	}



// 排序函数

	function objKeySort(arys) {
      //先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序
       var newkey = Object.keys(arys).sort();
       // console.log('newkey=' + newkey);
       var newObj = ''; //创建一个新的对象，用于存放排好序的键值对
       for (var i = 0; i < newkey.length; i++) {
           //遍历newkey数组
           newObj += [newkey[i]] + '=' + arys[newkey[i]] + '&';
       }
    return newObj.substring(0, newObj.length - 1); 
  }


// sha1 运算函数
    function add(x, y) {  
        return((x & 0x7FFFFFFF) + (y & 0x7FFFFFFF)) ^ (x & 0x80000000) ^ (y & 0x80000000);  
    }  
      
    function SHA1hex(num) {  
        var sHEXChars = "0123456789abcdef";  
        var str = "";  
        for(var j = 7; j >= 0; j--)  
            str += sHEXChars.charAt((num >> (j * 4)) & 0x0F);  
        return str;  
    }  
      
    function AlignSHA1(sIn) {  
        var nblk = ((sIn.length + 8) >> 6) + 1,  
            blks = new Array(nblk * 16);  
        for(var i = 0; i < nblk * 16; i++) blks[i] = 0;  
        for(i = 0; i < sIn.length; i++)  
            blks[i >> 2] |= sIn.charCodeAt(i) << (24 - (i & 3) * 8);  
        blks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);  
        blks[nblk * 16 - 1] = sIn.length * 8;  
        return blks;  
    }  
      
    function rol(num, cnt) {  
        return(num << cnt) | (num >>> (32 - cnt));  
    }  
      
    function ft(t, b, c, d) {  
        if(t < 20) return(b & c) | ((~b) & d);  
        if(t < 40) return b ^ c ^ d;  
        if(t < 60) return(b & c) | (b & d) | (c & d);  
        return b ^ c ^ d;  
    }  
      
    function kt(t) {  
        return(t < 20) ? 1518500249 : (t < 40) ? 1859775393 :  
            (t < 60) ? -1894007588 : -899497514;  
    }  
      
    function SHA1(sIn) {  
        var x = AlignSHA1(sIn);  
        var w = new Array(80);  
        var a = 1732584193;  
        var b = -271733879;  
        var c = -1732584194;  
        var d = 271733878;  
        var e = -1009589776;  
        for(var i = 0; i < x.length; i += 16) {  
            var olda = a;  
            var oldb = b;  
            var oldc = c;  
            var oldd = d;  
            var olde = e;  
            for(var j = 0; j < 80; j++) {  
                if(j < 16) w[j] = x[i + j];  
                else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);  
                t = add(add(rol(a, 5), ft(j, b, c, d)), add(add(e, w[j]), kt(j)));  
                e = d;  
                d = c;  
                c = rol(b, 30);  
                b = a;  
                a = t;  
            }  
            a = add(a, olda);  
            b = add(b, oldb);  
            c = add(c, oldc);  
            d = add(d, oldd);  
            e = add(e, olde);  
        }  
        SHA1Value = SHA1hex(a) + SHA1hex(b) + SHA1hex(c) + SHA1hex(d) + SHA1hex(e);  
        return SHA1Value.toUpperCase();  
    }  
      
    function SHA2(sIn) {  
        return SHA1(sIn).toLowerCase();  
    }

    function getQueryVariable(variable) //获取链接后面的参数和值
    {
           var query = window.location.search.substring(1);
           var vars = query.split("&");
           for (var i=0;i<vars.length;i++) {
                   var pair = vars[i].split("=");
                   if(pair[0] == variable){return pair[1];}
           }
           return(false);
    }


})(window)


